// 结算策略页面
const app = getApp()

Page({
  data: {
    userInfo: null,
    roomInfo: null,
    strategyData: null,
    loading: false,
    showSettlementConfirm: false
  },

  onLoad(options) {
    console.log('结算策略页面加载', options)
    this.checkUserAndRoom()
  },

  onShow() {
    // 每次显示时重新检查
    this.checkUserAndRoom()
  },

  // 检查用户和房间状态
  checkUserAndRoom() {
    console.log('检查用户和房间状态')
    const userInfo = wx.getStorageSync('userInfo') || app.globalData.userInfo
    const RoomCache = require('../../utils/roomCache')
    const roomData = RoomCache.getRoomBasicInfo()

    console.log('用户信息:', userInfo)
    console.log('房间数据:', roomData)
    console.log('API基础URL:', app.globalData.baseUrl)

    if (!userInfo) {
      console.log('用户未登录')
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/auth/auth'
        })
      }, 2000)
      return
    }

    if (!roomData || !roomData.id) {
      console.log('房间数据无效')
      wx.showToast({
        title: '请先加入房间',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/room/room'
        })
      }, 2000)
      return
    }

    this.setData({
      userInfo: userInfo
    })

    console.log('数据设置完成，开始获取房间信息和生成策略')
    // 获取完整房间信息
    this.getRoomInfo(roomData.id)
  },

  // 获取房间信息
  getRoomInfo(roomId) {
    console.log('获取房间信息:', roomId)
    wx.showLoading({
      title: '加载中...'
    })

    // 从房间缓存中获取房间代码
    const RoomCache = require('../../utils/roomCache')
    const roomData = RoomCache.getRoomBasicInfo()
    const roomCode = roomData ? roomData.room_code : null

    console.log('房间缓存数据:', roomData)
    console.log('房间代码:', roomCode)

    if (!roomCode) {
      wx.hideLoading()
      wx.showToast({
        title: '房间信息不完整',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: `${app.globalData.baseUrl}/api/room/get-by-code`,
      method: 'GET',
      data: {
        room_code: roomCode
      },
      success: (res) => {
        wx.hideLoading()
        console.log('房间信息获取成功:', res.data)
        
        if (res.data.success && res.data.data) {
          const roomInfo = res.data.data
          this.setData({
            roomInfo: roomInfo
          })
          
          // 获取房间信息后生成策略
          this.generateStrategy()
        } else {
          wx.showToast({
            title: res.data.message || '获取房间信息失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('获取房间信息失败:', error)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 生成结算策略
  generateStrategy() {
    const { userInfo, roomInfo } = this.data
    
    if (!userInfo || !roomInfo) {
      wx.showToast({
        title: '数据不完整',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/settlement-strategy/user-strategy`,
      method: 'GET',
      data: {
        user_id: userInfo.id,
        room_id: roomInfo.id
      },
      success: (res) => {
        this.setData({ loading: false })
        console.log('结算策略响应:', res.data)
        console.log('用户ID:', userInfo.id, '房间ID:', roomInfo.id)
        
        if (res.data.success) {
          console.log('策略数据:', res.data.data)
          this.setData({
            strategyData: res.data.data
          })
          console.log('策略类型:', res.data.data.strategy)
          console.log('策略消息:', res.data.data.message)
        } else {
          console.log('策略生成失败:', res.data.message)
          wx.showToast({
            title: res.data.message || '生成结算策略失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: (error) => {
        this.setData({ loading: false })
        console.error('生成结算策略失败:', error)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 保存结算策略
  saveStrategy() {
    const { roomInfo } = this.data
    
    if (!roomInfo) {
      wx.showToast({
        title: '房间信息不完整',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '保存结算中...',
      mask: true
    })

    wx.request({
      url: `${app.globalData.baseUrl}/api/settlement-strategy/save-strategy`,
      method: 'POST',
      data: {
        room_id: roomInfo.id,
        settlement_type: 'manual',
        settlement_reason: '用户生成结算策略'
      },
      success: (res) => {
        wx.hideLoading()
        console.log('保存策略响应:', res.data)
        
        if (res.data.success) {
          wx.showToast({
            title: '结算已保存',
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.data.message || '保存结算失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('保存结算失败:', error)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 分享策略
  shareStrategy() {
    const { strategyData } = this.data
    
    if (!strategyData) {
      wx.showToast({
        title: '没有策略可分享',
        icon: 'none'
      })
      return
    }

    let shareText = `我的结算策略：${strategyData.message}\n\n`
    
    if (strategyData.transfers && strategyData.transfers.length > 0) {
      shareText += '详细结算信息：\n'
      strategyData.transfers.forEach((transfer, index) => {
        shareText += `${index + 1}. ${transfer.from_username} → ${transfer.to_username}: ${transfer.amount}分\n`
      })
    }

    wx.setClipboardData({
      data: shareText,
      success: () => {
        wx.showToast({
          title: '策略已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  },

  // 查看房间整体策略
  viewRoomStrategy() {
    const { roomInfo } = this.data
    
    if (!roomInfo) {
      wx.showToast({
        title: '房间信息不完整',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '生成房间策略中...',
      mask: true
    })

    wx.request({
      url: `${app.globalData.baseUrl}/api/settlement-strategy/room-strategy`,
      method: 'GET',
      data: {
        room_id: roomInfo.id
      },
      success: (res) => {
        wx.hideLoading()
        console.log('房间策略响应:', res.data)
        
        if (res.data.success) {
          this.showRoomStrategy(res.data.data)
        } else {
          wx.showToast({
            title: res.data.message || '生成房间策略失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('生成房间策略失败:', error)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 显示房间策略
  showRoomStrategy(strategyData) {
    let content = strategyData.message + '\n\n'
    
    if (strategyData.transfers && strategyData.transfers.length > 0) {
      content += '详细结算信息：\n'
      strategyData.transfers.forEach((transfer, index) => {
        content += `${index + 1}. ${transfer.from_username} → ${transfer.to_username}: ${transfer.amount}分\n`
      })
    }

    wx.showModal({
      title: '房间整体结算策略',
      content: content,
      showCancel: true,
      cancelText: '关闭',
      confirmText: '保存策略',
      success: (res) => {
        if (res.confirm) {
          this.saveStrategy()
        }
      }
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  // 跳转到房间页面
  goToRoom() {
    wx.navigateTo({
      url: '/pages/room/room'
    })
  },

  // 取消结算
  cancelSettlement() {
    console.log('取消结算')
    wx.navigateBack()
  },

  // 确认结算
  confirmSettlement() {
    console.log('确认结算')
    this.setData({
      showSettlementConfirm: true
    })
  },

  // 隐藏结算确认弹框
  hideSettlementConfirm() {
    this.setData({
      showSettlementConfirm: false
    })
  },

  // 执行确认结算
  doConfirmSettlement() {
    const { roomInfo, userInfo } = this.data
    
    if (!roomInfo || !userInfo) {
      wx.showToast({
        title: '数据不完整',
        icon: 'none'
      })
      return
    }

    console.log('执行确认结算', roomInfo.id, userInfo.id)
    this.setData({
      showSettlementConfirm: false
    })
    
    wx.showLoading({
      title: '结算中...',
      mask: true
    })

    // 调用结算API
    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/room-settlement`,
      method: 'POST',
      data: {
        room_id: roomInfo.id,
        user_id: userInfo.id
      },
      success: (res) => {
        wx.hideLoading()
        console.log('结算响应:', res.data)
        
        if (res.data.success) {
          wx.showModal({
            title: '结算成功',
            content: '房间已结算，所有玩家已离开房间。是否创建新的一局继续游戏？',
            confirmText: '继续游戏',
            cancelText: '结束',
            success: (modalRes) => {
              if (modalRes.confirm) {
                // 继续游戏：跳转到创建房间页面（保持相同的房间名）
                wx.redirectTo({
                  url: `/pages/index/index?continue_game=1&room_name=${encodeURIComponent(roomInfo.name || '')}`
                })
              } else {
                // 结束游戏：返回首页
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '结算失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('结算失败:', error)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 广告点击处理
  onAdClick(e) {
    const type = e.currentTarget.dataset.type
    console.log('广告点击:', type)
    
    switch (type) {
      case 'games':
        wx.showToast({
          title: '更多游戏功能开发中',
          icon: 'none'
        })
        break
      case 'shop':
        wx.showToast({
          title: '积分商城功能开发中',
          icon: 'none'
        })
        break
      case 'invite':
        wx.showToast({
          title: '邀请好友功能开发中',
          icon: 'none'
        })
        break
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        })
    }
  }
})
